package com.leonzx.base.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class FileUtils {


    /**
     * 保存一个上传的文件<p>文件保存到 上传文件的根目录+dir.
     *
     * @param file 上传上来的MultipartFile
     * @param dir  文件需要保存的目录   Constants.FILE_TYPE_DIR_QM, Constants.FILE_TYPE_DIR_TZ
     * @return Attachment 附件
     */
    public static String uploadFile(MultipartFile file, String newFileName, String qz, String dir) {
        String oldName = file.getOriginalFilename();
        int index = oldName.lastIndexOf(".");
        //判断是否已经生成过
        String newName = newFileName + oldName.substring(index); //新文件名
        String path = qz + File.separator + dir + File.separator + newName;
        try {
            OSSUtils.upLoadMultipartFileByUrl(file, path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newName;
    }

    /**
     * 保存图片到服务器(特殊用途)
     *
     * @Author chen
     * @Date 2018/7/11 10:21
     */
    public static String uploadServiceFile(MultipartFile file, String newFilePath, String qz, String dir, HttpServletRequest request, HttpServletResponse response) {
        String oldName = file.getOriginalFilename();
        //判断是否已经生成过
        String serviceFilePath = qz + File.separator + dir + File.separator + newFilePath + File.separator + oldName;
        String path = request.getSession().getServletContext().getRealPath(qz) + File.separator + dir + File.separator + newFilePath;
        //保存文件
        File savePath = new File(path);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        File saveFile = new File(path + File.separator + oldName);
        try {
            file.transferTo(saveFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serviceFilePath;
    }

    /**
     * 删除文件
     */
    public static void deleteFile(String sPath) {
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }

    /**
     * 删除文件夹下边所有文件
     *
     * @param path
     */
    public static void deleteAllFilesOfDir(File path) {
        if (!path.exists())
            return;
        if (path.isFile()) {
            path.delete();
            return;
        }
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            deleteAllFilesOfDir(files[i]);
        }
        path.delete();
    }

}
